package cn.com.xinjinfu.pdoulcProduct.activity.user;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseActivity;
import cn.com.xinjinfu.pdoulcProduct.adapter.HuankuanAdapter;
import cn.com.xinjinfu.pdoulcProduct.common.ConstantValues;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.InvestBills;
import cn.com.xinjinfu.pdoulcProduct.entity.QianDaoBean;
import cn.com.xinjinfu.pdoulcProduct.entity.ReturnedInforbean;
import cn.com.xinjinfu.pdoulcProduct.entity.ReturnedInforbean.DateReceiveList;
import cn.com.xinjinfu.pdoulcProduct.entity.ReturnedInforbean.ReceiveTotalList;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.JSONManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.TitleManager;
import cn.com.xinjinfu.pdoulcProduct.manager.ToastManager;
import cn.com.xinjinfu.pdoulcProduct.manager.UIManager;
import cn.com.xinjinfu.pdoulcProduct.utils.TextViewUtil;
import cn.com.xinjinfu.pdoulcProduct.view.KCalendar;
import cn.com.xinjinfu.pdoulcProduct.view.ListViewForScrollView;
import cn.com.xinjinfu.pdoulcProduct.view.ReturnedKCalendar;
import cn.com.xinjinfu.pdoulcProduct.view.ReturnedKCalendar.OnCalendarClickListener;
import cn.com.xinjinfu.pdoulcProduct.view.ReturnedKCalendar.OnCalendarDateChangedListener;
import cn.com.xinjinfu.pdoulcProduct.view.ScrollViewExtend;

import static cn.com.xinjinfu.pdoulcProduct.entity.QianDaoBean.SignList;

/**
 * Created by android-adt on 2016/4/6.
 */
public class ReturnedCalendarAct extends BaseActivity {

    private String date = null;// 设置默认选中的日期  格式为 “2014-04-05” 标准DATE格式
    private TextView calendar_month,tv_top_title,tv_month,no_resiver,has_resiver,will_resiver;
    private ImageView qdangleleft,qdangleright;
    private ReturnedKCalendar calendar;
    private List<String> hasList = new ArrayList<String>(); //设置标记已还列表
    private List<String> willList = new ArrayList<String>();//设置标记待还列表
    private ArrayList<DateReceiveList> list = new ArrayList<DateReceiveList>();
    private RequestQueue requen;
    private ReturnedInforbean returnedInforbean;
    private RelativeLayout rl_bg;
    private LinearLayout hw_resiver;
    private List<ReceiveTotalList> receiveTotalLists;
    private List<DateReceiveList> dateReceiveLists;
    private HuankuanitemAdapter adapter;
    private ScrollViewExtend sv_include;
    private Dialog dg;
    private String theTime;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_returned);
        TitleManager.showTitle(this, "回款详情", "");
        requen = Volley.newRequestQueue(this);
        dg = UIManager.getLoadingDialog(this);
        dg.setCanceledOnTouchOutside(false);

        qdangleleft = (ImageView) findViewById(R.id.qdangleleft);
        qdangleright = (ImageView) findViewById(R.id.qdangleright);
        tv_top_title = (TextView) findViewById(R.id.tv_top_title);
        calendar_month = (TextView) findViewById(R.id.tv_calendar_month);
        tv_month = (TextView) findViewById(R.id.tv_month);
        no_resiver = (TextView) findViewById(R.id.no_resiver);
        has_resiver = (TextView) findViewById(R.id.has_resiver);
        will_resiver = (TextView) findViewById(R.id.will_resiver);
        hw_resiver = (LinearLayout) findViewById(R.id.hw_resiver);
        rl_bg = (RelativeLayout) findViewById(R.id.rl_bg);
        calendar = (ReturnedKCalendar) findViewById(R.id.popupwindow_calendar);
        /**************禁止ScrollView自动滑动到底部*********************/
        sv_include = (ScrollViewExtend) findViewById(R.id.sv_include);
        disableAutoScrollToBottom();
        ListViewForScrollView list_huikuan = (ListViewForScrollView) findViewById(R.id.list_huikuan);
        adapter = new HuankuanitemAdapter(this);
        list_huikuan.setAdapter(adapter);
        adapter.setList(list);

        Bundle bundle = getIntent().getExtras();
        date = bundle.getString("month");

        //如果进入到日历界面定位到制定月，可以用到这个方法
        if (null != date) {
            int years = Integer.parseInt(date.substring(0,date.indexOf("-")));
            int month = Integer.parseInt(date.substring(date.indexOf("-") + 1, date.indexOf("-") + 3));
            String myMonth = null;
            if (month < 10) {
                myMonth = "0" + month;
            } else {
                myMonth = "" + month;
            }
            calendar_month.setText(years + "年" + myMonth + "月");
            calendar.showCalendar(years, month);
            loginRequest(date);
        }
        qdangleleft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calendar.lastMonth();
            }
        });
        qdangleright.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calendar.nextMonth();
            }
        });
        //监听当前月份
        calendar.setOnCalendarDateChangedListener(new OnCalendarDateChangedListener() {
            public void onCalendarDateChanged(int year, int month) {
                calendar.removeAllBgColor();
                String myMonth = null;
                if (month < 10) {
                    myMonth = "0" + month;
                } else {
                    myMonth = "" + month;
                }
                calendar_month.setText(year + "年" + myMonth + "月");
                theTime = year + "-" + myMonth;
                loginRequest(theTime);
            }
        });

        //监听所选中的日期
        calendar.setOnCalendarClickListener(new OnCalendarClickListener() {
            public void onCalendarClick(int row, int col, String dateFormat) {
                int month = Integer.parseInt(dateFormat.substring(
                        dateFormat.indexOf("-") + 1,
                        dateFormat.lastIndexOf("-")));
                if (calendar.getCalendarMonth() - month == 1//跨年跳转
                        || calendar.getCalendarMonth() - month == -11) {
                    calendar.lastMonth();
                } else if (month - calendar.getCalendarMonth() == 1 //跨年跳转
                        || month - calendar.getCalendarMonth() == -11) {
                    calendar.nextMonth();
                } else {
                    calendar.removeAllBgColor();
                    if (receiveTotalLists!=null) {
                        for (ReceiveTotalList receiveTotalList : receiveTotalLists) {
                            L.d("dateFormat=======" + dateFormat + "getRc_date()====" + receiveTotalList.getRc_date());
                            if (dateFormat.equals(receiveTotalList.getRc_date())) {
                                showDayInfor(receiveTotalList);
                            }
                        }
                    }
                    if (dateReceiveLists!=null){
                        //对应当天的回款详情展示
                        createReceiveList(dateReceiveLists, dateFormat);
                    }
                    //非标记的天
                    if (!hasList.contains(dateFormat) && !willList.contains(dateFormat)){
                        String day = dateFormat.substring(dateFormat.indexOf("-") + 4, dateFormat.length());
                        tv_month.setText(day);
                        calendar.setCalendarDayBgColor(dateFormat, R.drawable.calendar_day_bg2);
                        rl_bg.setBackgroundColor(0xffCCCCCC);
                        no_resiver.setVisibility(View.VISIBLE);
                        hw_resiver.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    private void upData(){
        receiveTotalLists = returnedInforbean.getReceiveTotalList();
        dateReceiveLists = returnedInforbean.getDateReceiveList();
        if (receiveTotalLists!=null){
            for (ReceiveTotalList receiveTotalList:receiveTotalLists){
                if (receiveTotalList.getWr_amount()>0) {
                    willList.add(receiveTotalList.getRc_date());
                    calendar.addMarks(willList, R.drawable.text_shape2);
                }else{
                    hasList.add(receiveTotalList.getRc_date());
                    calendar.addMarks(hasList, R.drawable.text_shape3);
                }
            }
            //选择默认第一个带标记的天，设置对应的背景
            showDayInfor(receiveTotalLists.get(0));
        }else {
            //选择默认每月第一天，设置对应的背景
            String dateFormat = theTime + "-01";
            tv_month.setText("01");
            calendar.setCalendarDayBgColor(dateFormat, R.drawable.calendar_day_bg2);
            rl_bg.setBackgroundColor(0xffCCCCCC);
            no_resiver.setVisibility(View.VISIBLE);
            hw_resiver.setVisibility(View.GONE);
        }
        if (dateReceiveLists!=null){
            //对应第一天的回款详情展示
            createReceiveList(dateReceiveLists, receiveTotalLists.get(0).getRc_date());
        }else {
            list.clear();
            adapter.notifyDataSetChanged();
        }
    }

    public void createReceiveList(List<DateReceiveList> receiveLists,String day){
        list.clear();
        for (DateReceiveList item:receiveLists){
            if (item.getRc_time().equals(day)){
                DateReceiveList item2 = new DateReceiveList();
                item2.setWr_interest(item.getWr_interest());
                item2.setHr_corpus(item.getHr_corpus());
                item2.setStatus(item.getStatus());
                item2.setHr_interest(item.getHr_interest());
                item2.setWr_corpus(item.getWr_corpus());
                item2.setRc_time(item.getRc_time());
                item2.setIsben(true);
                if (item.getWr_interest() != 0)
                    list.add(item);
                if (item.getWr_corpus() != 0)
                    list.add(item2);
                if (item.getHr_interest() != 0)
                    list.add(item);
                if (item.getHr_corpus() != 0)
                    list.add(item2);
            }
        }
        adapter.notifyDataSetChanged();
        L.d("第"+day+"天-----------"+"listSize======================" + list.size());
    }

    public void showDayInfor(ReceiveTotalList receiveTotalList){
        String thisData = receiveTotalList.getRc_date();
        String day = thisData.substring(thisData.indexOf("-") + 4, thisData.length());
        if (receiveTotalList.getWr_amount()>0) {
            rl_bg.setBackgroundColor(0xffF4B942);
            has_resiver.setVisibility(View.GONE);
            will_resiver.setVisibility(View.VISIBLE);
            calendar.setCalendarDayBgColor(thisData, R.drawable.calendar_day_bg4);//黄色
            if (receiveTotalList.getHr_amount()>0){
                has_resiver.setVisibility(View.VISIBLE);
                will_resiver.setVisibility(View.VISIBLE);
            }
        }else {
            calendar.setCalendarDayBgColor(thisData, R.drawable.calendar_day_bg3);//蓝色
            has_resiver.setVisibility(View.VISIBLE);
            will_resiver.setVisibility(View.GONE);
            rl_bg.setBackgroundColor(0xff6ED3D6);
        }
        tv_month.setText(day);
        no_resiver.setVisibility(View.GONE);
        hw_resiver.setVisibility(View.VISIBLE);
        has_resiver.setText("已还 " + TextViewUtil.getSumLength(receiveTotalList.getHr_amount()));
        will_resiver.setText("待还 "+TextViewUtil.getSumLength(receiveTotalList.getWr_amount()));
    }

    /**
     * 网络请求
     */
    private void loginRequest(String time) {
        dg.show();
        User user = AccountManager.getInstance().getUser();
        if (user != null) {
            final Map<String, String> parameters = DataHandler.getParameters("1418");
            parameters.put("id", user.getCurrUser().getSign());
            parameters.put("yearMonth",time);
            JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, error);
            request.setRetryPolicy(new DefaultRetryPolicy(ConstantValues.TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            requen.add(request);
        }
    }
    private Response.ErrorListener error = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dg.dismiss();
            DataHandler.errorHandler(ReturnedCalendarAct.this, error);
        }
    };

    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.d("回款详情 ==========" + jobj);
            dg.dismiss();
            if (JSONManager.getError(jobj) == -1){
                returnedInforbean = JSON.parseObject(jobj.toString(), ReturnedInforbean.class);
                if (returnedInforbean != null) {
                    upData();
                }
            }
        }
    };


    private void disableAutoScrollToBottom() {
        sv_include.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
        sv_include.setFocusable(true);
        sv_include.setFocusableInTouchMode(true);
        sv_include.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.requestFocusFromTouch();
                return false;
            }
        });
    }

}
class HuankuanitemAdapter extends BaseAdapter {
    private ArrayList<DateReceiveList> mlist;
    private Activity context;
    private LayoutInflater inflater;
    public void setList(ArrayList<DateReceiveList> list) {
        this.mlist = list;
    }
    public HuankuanitemAdapter(Activity context) {
        inflater = LayoutInflater.from(context);
        this.context = context;
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return mlist == null ? 0 : mlist.size();
    }
    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return mlist.get(position);
    }
    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if(convertView==null){
            holder=new ViewHolder();
            convertView=inflater.inflate(R.layout.item_huikuanjihua_info, null);
            holder.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
            holder.tv_huankuan_state = (TextView) convertView.findViewById(R.id.tv_huankuan_state);
            holder.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
            holder.tv_money = (TextView) convertView.findViewById(R.id.tv_money);
            holder.tv_lixi = (TextView) convertView.findViewById(R.id.tv_lixi);
            holder.tv_benjin = (TextView) convertView.findViewById(R.id.tv_benjin);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }
        DateReceiveList mitem = mlist.get(position);
        L.d("mitem======================"+mitem.toString()+"position==="+position);
        convertView.setVisibility(View.VISIBLE);
        GradientDrawable myGrad = (GradientDrawable)holder.tv_huankuan_state.getBackground();
        if (mitem.getStatus() == -1){
            holder.tv_huankuan_state.setText("未收款");
            myGrad.setColor(0xFFcccccc);
            if(mitem.isben()){
                holder.tv_money.setText(TextViewUtil.getSumLength(mitem.getWr_corpus()));
            }else{
                holder.tv_money.setText(TextViewUtil.getSumLength(mitem.getWr_interest()));
            }
        }else if(mitem.getStatus() == 0){
            holder.tv_huankuan_state.setText("正常收款");
            myGrad.setColor(0xFF6ED3D6);
            if(mitem.isben()){
                holder.tv_money.setText(TextViewUtil.getSumLength(mitem.getHr_corpus()));
            }else{
                holder.tv_money.setText(TextViewUtil.getSumLength(mitem.getHr_interest()));
            }
        }
        if(mitem.isben()){
            holder.tv_benjin.setVisibility(View.VISIBLE);
            holder.tv_lixi.setVisibility(View.GONE);
        }else{
            holder.tv_benjin.setVisibility(View.GONE);
            holder.tv_lixi.setVisibility(View.VISIBLE);
        }
        holder.tv_time.setText(mitem.getRc_time());
        if (mitem.getTitle() != null){
            holder.tv_title.setVisibility(View.VISIBLE);
            holder.tv_title.setText(mitem.getTitle());
        }else {
            holder.tv_title.setVisibility(View.GONE);
        }
        return convertView;
    }

    class ViewHolder{
        TextView tv_title;
        TextView tv_huankuan_state;
        TextView tv_time;
        TextView tv_money;
        TextView tv_lixi;
        TextView tv_benjin;
    }
}